package io.github.mosiki.modules.sys.service.impl;

import io.github.mosiki.modules.sys.domain.SysUserRole;
import io.github.mosiki.modules.sys.repository.SysUserRoleRepository;
import io.github.mosiki.modules.sys.service.SysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service("sysUserRoleService")
public class SysUserRoleServiceImpl implements SysUserRoleService {
    @Autowired
    private SysUserRoleRepository sysUserRoleRepository;

    @Override
    public List<Long> listRoleId(Long userId) {
        return sysUserRoleRepository.listRoleId(userId);
    }

    @Override
    public void saveOrUpdate(Long userId, List<Long> roleIdList) {
        //先删除用户与角色关系
        this.deleteByUserId(userId);

        if(roleIdList == null || roleIdList.size() == 0){
            return ;
        }

        //保存用户与角色关系
        List<SysUserRole> list = new ArrayList<>(roleIdList.size());
        for(Long roleId : roleIdList){
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(userId);
            sysUserRole.setRoleId(roleId);

            list.add(sysUserRole);
        }
        sysUserRoleRepository.saveAll(list);
    }

    private void deleteByUserId(Long userId) {
        
        int count = sysUserRoleRepository.deleteByUserId(userId);
    }

    @Override
    @Transactional
    public void deleteBatch(Long[] roleIds) {
        sysUserRoleRepository.deleteByRoleId(roleIds);
    }
}
